package com.example.nettydemo.bio_2;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 * @author juzhenxing
 * @date 2020/11/4
 * @description
 */
@Slf4j
public class TimeServerHandler implements Runnable {

    private Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            String currentTime = null;
            String body = null;

            while (true) {
                // 读取结束的标识为\n
                in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
                body = in.readLine();
                if (body == null) {
                    return;
                }

                log.info("request: [{}]", body);
                currentTime = "abc".equals(body) ? new Date().toString() : "请求失败";
                log.info("response: [{}]", currentTime);

                out = new PrintWriter(this.socket.getOutputStream(), true);
                out.println(currentTime);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            if (out != null) {
                out.close();
                out = null;
            }

            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                this.socket = null;
            }
        }
    }
}
